package com.test;

public class BinaryTree {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode(int val) {
            this.val = val;
            this.left = null;
            this.right = null;
        }
    }

    TreeNode root;

    public BinaryTree() {
        this.root = null;
    }

    // 构建二叉树
    private TreeNode buildTree(int n) {
        if (n <= 0) {
            return null;
        }
        root = new TreeNode(1);
        TreeNode[] nodes = new TreeNode[n + 1];
        nodes[1] = root;
        for (int i = 2; i <= n; i++) {
            int parentIndex = (i - 1) / 2;
            TreeNode parent = nodes[parentIndex];
            TreeNode newNode = new TreeNode(i);
            if (i % 2 == 0) { // 偶数放右子树
                parent.right = newNode;
            } else { // 奇数放左子树
                parent.left = newNode;
            }
            nodes[i] = newNode;
        }
        return root;
    }

    // 先序遍历打印二叉树结构
    private void printTreeStructure(TreeNode node, int level) {
        if (node == null) {
            return;
        }
        for (int i = 0; i < level; i++) {
            System.out.print("  "); // 缩进表示层次结构
        }
        System.out.println(node.val); // 输出节点值
        printTreeStructure(node.left, level + 1); // 递归打印左子树
        printTreeStructure(node.right, level + 1); // 递归打印右子树
    }

    // 打印二叉树结构
    public void printStructure() {
        printTreeStructure(root, 0);
    }

    public static void main(String[] args) {
        int n = 12; // 给定的数字，用于构建二叉树

        BinaryTree tree = new BinaryTree();
        tree.root = tree.buildTree(n);

        System.out.println("二叉树结构：");
        tree.printStructure();
    }
}